package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public void updateStatus(Long id, Integer status) {
        // 1. 根据id查询商品
//        Item item = this.getById(id);// 弃用，查库浪费性能
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        // 2. 更新商品
        this.updateById(item);
        // lambda
        // update().set("status", status).eq("id", id).update();
        // 多个属性
        // update().set("status", status).set("name", name).eq("id", id).update();

        // 3. 发送消息
        String exchangeName = "item.topic";
        String routingKey = status == 1 ? "item.up" : "item.down";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, id);
        log.info("[发送上下架消息]id:{}, 状态:{}", id, status);
    }

    @Override
    public void deduct(Long itemId, Integer num) {
        // 根据id查商品
        Item item = this.getById(itemId);
        item.setStock(item.getStock() - num);
        this.updateById(item);
    }
}
